<template>
  <!-- 搜索建议 -->
  <div>
    <van-cell v-for="item in list" :key="item" icon="search" @click="clickSuggestion(item)">
      <div slot="title" v-html="format(item)"></div>
    </van-cell>
  </div>
</template>

<script>
import { debounce } from 'lodash'
import { getSearchSuggestions } from '@/api/search.js'
export default {
  props: {
    // 父组件输入框的值
    text: {
      type: String,
      require: true
    }
  },
  data () {
    return {
      // 定时器
      // timer: null
      // 搜索建议数据
      list: [],
      // 是否发起请求
      isShow: true
    }
  },
  methods: {
    // 获取搜索建议列表
    async getSearchSuggestionList () {
      try {
        const { data: res } = await getSearchSuggestions(this.text)
        this.list = res.data.options
      } catch (err) {
        this.$toast('获取搜索建议失败')
      }
    },
    // 搜索推荐高亮
    format (item) {
      const reg = new RegExp(this.text, 'gi')
      return item.replace(reg, `<span style="color:red;">${this.text}</span>`)
    },
    // 点击推荐搜索
    clickSuggestion (item) {
      this.$emit('search', item)
    }
  },
  computed: {},
  watch: {
    // 监听输入框值的改变
    text: {
      // text变化触发
      // handler (newText) {
      //   // 防抖
      //   clearTimeout(this.timer)
      //   this.timer = setTimeout(() => {
      //     console.log(1)
      //   }, 600)
      // },
      handler: debounce(function (newText) {
        // 解决搜索框中值删完还会发送一次请求
        if (!this.isShow) return
        this.getSearchSuggestionList()
      }, 600),
      // 首次也会触发
      immediate: true
    }
  },
  filters: {},
  components: {},
  created () { },
  mounted () { },
  beforeDestroy () {
    // 销毁时让最后一次请求不发送
    this.isShow = false
  }
}
</script>

<style scoped lang='less'>
</style>
